package com.wichell.framework.util;

import org.apache.commons.lang.StringEscapeUtils;

import com.thoughtworks.xstream.XStream;

/**   
 * @ClassName:  XmlUtil 
 * @Description:XML处理工具类
 * @author: Isaac
 * @date:   2018年2月12日 上午11:34:41   
 *     
 * @Copyright: 2018 www.wichell.com Inc. All rights reserved.
 */
public class XmlUtil {

	/**
	 * java 转换成xml
	 * @Title: toXml 
	 * @Description: TODO 
	 * @param obj 对象实例
	 * @return String xml字符串
	 */
	public static String toXml(Object obj) {
		XStream xstream = new XStream();
		xstream.processAnnotations(obj.getClass());
		String responseXml = xstream.toXML(obj);
		return StringEscapeUtils.unescapeXml(responseXml);
	}

	/**
	 *  将传入xml文本转换成Java对象
	 * @Title: toBean 
	 * @Description: TODO 
	 * @param xmlStr
	 * @param cls  xml对应的class类
	 * @return T   xml对应的class类的实例对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T toBean(String xmlStr, Class<T> cls) {
		XStream xstream = new XStream();
		xstream.processAnnotations(cls);
		T obj = (T) xstream.fromXML(xmlStr);
		return obj;
	}
}